package com.lyx.rpc.consumer.common.helper;

import com.lyx.rpc.consumer.common.RpcConsumer;
import com.lyx.rpc.consumer.common.handler.RpcConsumerHandler;
import com.lyx.rpc.protocol.meta.ServiceMeta;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author by lyx
 */
public class RpcConsumerHandlerHelper {
    private static Map<String, RpcConsumerHandler> rpcConsumerHandlerMap;

    static {
        rpcConsumerHandlerMap = new ConcurrentHashMap<>();
    }

    private static String getKey(ServiceMeta serviceMeta) {
        return serviceMeta.getServiceAddr().concat("_").concat(String.valueOf(serviceMeta.getPort()));
    }

    public static void put(ServiceMeta serviceMeta, RpcConsumerHandler rpcConsumerHandler) {
        rpcConsumerHandlerMap.put(getKey(serviceMeta), rpcConsumerHandler);
    }

    public static RpcConsumerHandler get(ServiceMeta serviceMeta) {
        return rpcConsumerHandlerMap.get(getKey(serviceMeta));
    }

    public static void closeRpcConsumerHandler() {
        Collection<RpcConsumerHandler> handlers = rpcConsumerHandlerMap.values();
        if (handlers != null && !handlers.isEmpty()) {
            handlers.forEach((handler) -> {
                handlers.clear();
            });
        }
        rpcConsumerHandlerMap.clear();
    }
}
